﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Mvc.Html;

namespace Infrastructure.Web.Mvc.Extensions
{
    public static partial class HtmlHelperExtensions
    {
        public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expr, string viewName)
        {
            string name = ExpressionHelper.GetExpressionText(expr);
            object model = ModelMetadata.FromLambdaExpression(expr, helper.ViewData).Model;
            return helper.Partial(viewName, model, new ViewDataDictionary(helper.ViewData) { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = name } });
        }

        public static void RenderAction<TController>(this HtmlHelper helper, Expression<Action<TController>> action) where TController : Controller
        {
            RouteValueDictionary routeValuesFromExpression = Utils.GetRouteValuesFromExpression<TController>(action);
            helper.RenderRoute(routeValuesFromExpression);
        }

        public static void RenderRoute(this HtmlHelper helper, RouteValueDictionary routeValues)
        {
            RouteData routeData = new RouteData();
            foreach (KeyValuePair<string, object> pair in routeValues)
            {
                routeData.Values.Add(pair.Key, pair.Value);
            }
            HttpContextBase httpContext = helper.ViewContext.HttpContext;
            RequestContext context = new RequestContext(httpContext, routeData);
            new RenderActionMvcHandler(context).ProcessRequestInternal(httpContext);
        }

        public static MvcHtmlString RenderHtml(this HtmlHelper helper, string strValue)
        {
            return new MvcHtmlString(strValue);
        }
    }

    internal class RenderActionMvcHandler : MvcHandler
    {
        public RenderActionMvcHandler(RequestContext context)
            : base(context)
        {
        }

        protected override void AddVersionHeader(HttpContextBase httpContext)
        {
        }

        public void ProcessRequestInternal(HttpContextBase httpContext)
        {
            base.ProcessRequest(httpContext);
        }
    }
}
